package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"user-membership/rpc/model/mysql"
	"user-membership/rpc/model/redis"
	"user-membership/rpc/pkg"

	"user-membership/rpc/goods"
	"user-membership/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *goods.CreateOrderReq) (*goods.CreateOrderResp, error) {
	g := mysql.Goods{}
	err := g.GetGoodsInfo(int(in.GoodsId))
	if err != nil {
		logx.Error("创建订单失败", err)
		return nil, errors.New("创建订单失败")
	}
	if g.ID == 0 {
		logx.Error("商品不存在", err)
		return nil, errors.New("商品不存在")
	}
	stock := redis.GetGoodsStock(int(in.GoodsId))
	if stock < in.Num {
		logx.Error("商品库存不足", err)
		return nil, errors.New("商品库存不足")
	}
	orderSn := uuid.NewString()
	amount := g.GoodsPrice * float64(in.Num)
	o := mysql.Order{
		OrderSn: orderSn,
		UserId:  int(in.UserId),
		Amount:  amount,
		Payment: int(in.Payment),
		Status:  1,
	}
	err = o.Create()
	if err != nil {
		logx.Error("创建订单失败", err)
		return nil, errors.New("创建订单失败")
	}
	oG := mysql.OrderGoods{
		OrderSn:    orderSn,
		GoodsId:    int(in.GoodsId),
		GoodsTitle: g.GoodsTitle,
		Price:      g.GoodsPrice,
		Num:        in.Num,
		GoodsImg:   g.GoodsImg,
	}
	err = oG.Create()
	if err != nil {
		logx.Error("创建订单商品失败", err)
		return nil, errors.New("创建订单商品失败")
	}
	amountStr := fmt.Sprintf("%.2f", amount)
	payUrl := pkg.Alipay(orderSn, amountStr)
	return &goods.CreateOrderResp{
		PayUrl: payUrl,
	}, nil
}
